package com.googlecode.spruce.web.admin.host;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.googlecode.spruce.dao.HostDao;
import com.googlecode.spruce.dao.ServiceResultDao;
import com.googlecode.spruce.domain.ServiceResult;

@Controller
@RequestMapping("/admin/host")
public class HostResults
{

    private static final int PAGE_SIZE = 30;

    @Autowired
    private HostDao hostDao;

    @Autowired
    private ServiceResultDao serviceResultDao;

    @RequestMapping(value = "/results.do", method = RequestMethod.GET)
    public ModelAndView getAll(@RequestParam("hostid") Integer hostID,
            @RequestParam(value = "pageid", defaultValue = "0") Integer pageID)
    {
        Assert.isTrue(pageID >= 0);

        final ModelAndView model = new ModelAndView("host/results");

        final int pageOffset = (pageID * PAGE_SIZE);

        final List<ServiceResult> results = this.serviceResultDao.getPageByHostID(hostID, pageOffset, PAGE_SIZE);

        int prevPageID = 0;
        int nextPageID = pageID;

        if (pageID > 0)
        {
            prevPageID = pageID - 1;
        }

        if (PAGE_SIZE == results.size())
        {
            nextPageID = pageID + 1;
        }

        model.addObject("hostID", hostID);
        model.addObject("results", results);
        model.addObject("prevPageID", prevPageID);
        model.addObject("nextPageID", nextPageID);

        return model;
    }
}
